package com.ml4ai.backend.services.impl;

import com.ml4ai.backend.domain.Menu;
import com.ml4ai.backend.dto.MenuDTO;
import com.ml4ai.backend.repository.MenuRepository;
import com.ml4ai.backend.services.MenuService;
import com.ml4ai.backend.services.base.impl.BaseServiceImpl;
import com.ml4ai.backend.services.mappers.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.function.Function;

/**
 * Created by uesr on 2018/9/3.
 */
@Service
@Transactional
public class MenuServiceImpl extends BaseServiceImpl<Menu, MenuDTO> implements MenuService {

    @Autowired
    MenuRepository menuRepo;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public JpaRepository<Menu, Long> getRepository() {
        return menuRepo;
    }

    @Override
    public Function<Menu, MenuDTO> getConvertEntity2DTOFunction() {
        return menuMapper::e2d;
    }

    @Override
    public Function<MenuDTO, Menu> getConvertDTO2EntityFunction() {
        return menuMapper::d2e;
    }

    @Override
    public List<MenuDTO> getAllMenus() {
        MenuDTO queryRoot = new MenuDTO();
        queryRoot.setParentIsNull(true);
        queryRoot.setStatus("1");
        List<MenuDTO> rootList = query(queryRoot);
        for (MenuDTO menuDTO : rootList) {
            setChildren(menuDTO);
        }
        return rootList;
    }

    private void setChildren(MenuDTO menuDTO) {
        MenuDTO queryChildren = new MenuDTO();
        queryChildren.setStatus("1");
        queryChildren.setParentId(menuDTO.getId());
        List<MenuDTO> children = query(queryChildren);
        for (MenuDTO childrenDTO : children) {
            setChildren(childrenDTO);
        }
        menuDTO.setChildren(children);
    }


}
